package com.woniuxy.ai.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.ai.callback.StreamProcessor;
import com.woniuxy.ai.entity.AIChatLog;
import com.woniuxy.ai.entity.Faq;
import com.woniuxy.ai.mapper.AIChatLogMapper;
import com.woniuxy.ai.mapper.FaqMapper;
import com.woniuxy.ai.util.SimilarityClient;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AIChatService {

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build();

    private static final String DEEPSEEK_API_KEY = "sk-fec3162a763f4774842f6e87338cda05";
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";

    @Autowired
    private AIChatLogMapper aiChatLogMapper;
    @Autowired
    private FaqMapper faqMapper;

    // 流式处理AI聊天
    public void chatWithAIStream(String userInput, String sessionId, StreamProcessor processor) throws IOException {
        // 1. 先尝试精确查询
        Faq exactMatch = faqMapper.findByQuestion(userInput);

        if (exactMatch != null && exactMatch.getIsActive() == 1) {
            // 如果找到精确匹配，直接发送答案
            sendRawAnswer(processor, exactMatch.getAnswer());
            return;
        }

        // 2. 如果没有精确匹配，尝试使用远程模型进行语义匹配
        List<Faq> allFaqs = faqMapper.findAllActiveFaqs(); // 查询所有有效的FAQ

        if (!allFaqs.isEmpty()) {
            // 使用远程模型服务计算语义相似度并选择最佳匹配
            Faq bestMatch = findBestMatchWithRemoteModel(userInput, allFaqs);
            if (bestMatch != null) {
                sendRawAnswer(processor, bestMatch.getAnswer());
                return;
            }
        }
// 1. 获取最近3轮对话历史（可根据需要调整）
        List<AIChatLog> history = aiChatLogMapper.selectList(
                new QueryWrapper<AIChatLog>()
                        .eq("session_id", sessionId)
                        .orderByDesc("create_time")
                        .last("LIMIT 3")
        );
        Collections.reverse(history); // 按时间正序排列

        // 构建上下文消息
        List<JSONObject> messages = new ArrayList<>();

// 添加历史对话
        for (AIChatLog log : history) {
            messages.add(new JSONObject()
                    .fluentPut("role", "user")
                    .fluentPut("content", log.getUserInput()));
            messages.add(new JSONObject()
                    .fluentPut("role", "assistant")
                    .fluentPut("content", log.getAiResponse()));
        }

// 添加当前问题
        messages.add(new JSONObject()
                .fluentPut("role", "user")
                .fluentPut("content", userInput));

// 将messages列表转换为JSON数组字符串
        JSONArray messagesArray = new JSONArray(messages);


        // 3. 如果都没有匹配，调用AI生成回答
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", userInput);

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", messagesArray);
        requestBody.put("stream", true);
        requestBody.put("temperature", 0.9);

        RequestBody body = RequestBody.create(
                requestBody.toJSONString(),
                MediaType.get("application/json")
        );

        Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + DEEPSEEK_API_KEY)
                .addHeader("Accept", "text/event-stream")
                .build();

        client.newCall(request).enqueue(new Callback() {
            private final StringBuilder fullResponse = new StringBuilder();
            private String lastPartialSentence = ""; // 用于跟踪部分句子

            @Override
            public void onFailure(Call call, IOException e) {
                processor.onError(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    processor.onError(new IOException("Unexpected code " + response));
                    return;
                }

                try (ResponseBody responseBody = response.body()) {
                    if (responseBody == null) {
                        processor.onError(new IOException("Empty response body"));
                        return;
                    }

                    BufferedReader reader = new BufferedReader(responseBody.charStream());
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data: ")) {
                            String data = line.substring(6).trim();
                            if (data.equals("[DONE]")) {
                                continue;
                            }

                            String content = extractContentFromJson(data);
                            if (content != null && !content.isEmpty()) {
                                // 智能分段逻辑
                                String processedContent = processContentForNewlines(content);
                                fullResponse.append(processedContent);
                                processor.onChunk(processedContent);
                            }
                        }
                    }

                    // 4. 保存记录时添加会话信息
                    AIChatLog log = new AIChatLog();
                    log.setUserInput(userInput);
                    log.setAiResponse(fullResponse.toString());
                    log.setSessionId(sessionId);
                    log.setTurnNumber(history.isEmpty() ? 1 : history.size() + 1);
                    aiChatLogMapper.insert(log);

                    processor.onComplete();
                } catch (Exception e) {
                    processor.onError(e);
                }
            }


            // 新增：智能分段处理
            private String processContentForNewlines(String content) {
                // 按句子分段（以句号、问号、感叹号结尾）
                String[] sentences = content.split("(?<=[.!?])\\s+");
                StringBuilder result = new StringBuilder();
                for (String sentence : sentences) {
                    result.append(sentence).append("\n"); // 每个句子后加换行
                }
                return result.toString().trim();
            }
        });
    }

    // 普通处理AI聊天
    public String chatWithAI(String userInput) throws IOException {
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", userInput);

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", new JSONObject[]{message});

        RequestBody body = RequestBody.create(
                requestBody.toJSONString(),
                MediaType.get("application/json")
        );

        Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + DEEPSEEK_API_KEY)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            String responseBody = response.body().string();
            String aiResponse = extractContentFromFullResponse(responseBody);

            AIChatLog log = new AIChatLog();
            log.setUserInput(userInput);
            log.setAiResponse(aiResponse);
            aiChatLogMapper.insert(log);

            return aiResponse;
        }
    }
    // 直接发送原始答案
    private void sendRawAnswer(StreamProcessor processor, String answer) throws IOException {
        for (char c : answer.toCharArray()) {
            processor.onChunk(String.valueOf(c));
            try {
                Thread.sleep(30); // 控制输出速度
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        processor.onComplete();
    }
    private String extractContentFromJson(String json) {
        try {
            JSONObject obj = JSON.parseObject(json);
            return obj.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("delta")
                    .getString("content");
        } catch (Exception e) {
            log.debug("解析流式响应片段失败: {}", json);
            return "";
        }
    }

    private String extractContentFromFullResponse(String json) {
        try {
            JSONObject obj = JSON.parseObject(json);
            return obj.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content");
        } catch (Exception e) {
            log.error("解析 AI 回答失败", e);
            return "抱歉，我无法理解你的问题。";
        }
    }
    public String fetchDataFromExternalAPI(String apiUrl) throws IOException {
        Request request = new Request.Builder()
                .url(apiUrl)
                .get()
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("External API request failed: " + response);
            }
            return response.body().string();
        }
    }
    public String analyzeDataWithAI(String rawData) throws IOException {
        String prompt = "请分析以下 JSON 数据，并生成结构化的分析结果（包含图表数据和结论），返回格式为 JSON。" +
                "只返回json，不要有任何其他的描述语句,确保接口返回的数据结构是以下结构，内容不固定：" +
                "{\n" +
                "  \"analysisText\": ,\n" +
                "  \"charts\": [\n" +
                "    {\n" +
                "      \"type\": \"pie\",\n" +
                "      \"title\": \"巡更计划周期分布\",\n" +
                "      \"series\": [\n" +
                "        {\n" +
                "          \"name\": \"计划数量\",\n" +
                "          \"type\": \"pie\",\n" +
                "          \"data\": [\n" +
                "            { \"value\": , \"name\": \"每日\" },\n" +
                "            { \"value\": , \"name\": \"每周\" },\n" +
                "            { \"value\": , \"name\": \"每月\" }\n" +
                "          ]\n" +
                "        }\n" +
                "      ]\n" +
                "    },\n" +
                "    {\n" +
                "      \"type\": \"bar\",\n" +
                "      \"title\": \"\",\n" +
                "      \"series\": [\n" +
                "        {\n" +
                "          \"name\": \"巡更次数\",\n" +
                "          \"type\": \"bar\",\n" +
                "          \"data\": [\n" +
                "            { \"name\": \"\", \"value\":  },\n" +
                "            { \"name\": \"\", \"value\":  },\n" +
                "            { \"name\": \"\", \"value\":  },\n" +
                "            { \"name\": \"\", \"value\":  }\n" +
                "          ]\n" +
                "        }\n" +
                "      ],\n" +
                "      \"xAxis\": {\n" +
                "        \"type\": \"category\",\n" +
                "        \"data\": [\"\", \"\", \"\", \"\"]\n" +
                "      }\n" +
                "    },\n" +
                "    {\n" +
                "      \"type\": \"line\",\n" +
                "      \"title\": \"月度巡更完成率趋势\",\n" +
                "      \"series\": [\n" +
                "        {\n" +
                "          \"name\": \"完成率\",\n" +
                "          \"type\": \"line\",\n" +
                "          \"data\": [\n" +
                "            { \"name\": \"月\", \"value\":  },\n" +
                "            { \"name\": \"月\", \"value\":  },\n" +
                "            { \"name\": \"月\", \"value\":  },\n" +
                "            { \"name\": \"月\", \"value\":  },\n" +
                "            { \"name\": \"月\", \"value\":  },\n" +
                "            { \"name\": \"月\", \"value\":  }\n" +
                "          ]\n" +
                "        }\n" +
                "      ],\n" +
                "      \"xAxis\": {\n" +
                "        \"type\": \"category\",\n" +
                "        \"data\": [\"月\", \"月\", \"月\", \"月\", \"月\", \"月\"]\n" +
                "      }\n" +
                "    }\n" +
                "  ],\n" +
                "  \"detailTable\": {\n" +
                "    \"columns\": [\n" +
                "      { \"title\": \"执行人\", \"key\": \"executor\" },\n" +
                "      { \"title\": \"计划类型\", \"key\": \"planType\" },\n" +
                "      { \"title\": \"频次\", \"key\": \"frequency\" },\n" +
                "      { \"title\": \"重点内容\", \"key\": \"content\" }\n" +
                "    ],\n" +
                "    \"data\": [\n" +
                "      {\n" +
                "        \"executor\": \"\",\n" +
                "        \"planType\": \"\",\n" +
                "        \"frequency\": \"\",\n" +
                "        \"content\": \"\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"executor\": \"\",\n" +
                "        \"planType\": \"\",\n" +
                "        \"frequency\": \"\",\n" +
                "        \"content\": \"\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"executor\": \"\",\n" +
                "        \"planType\": \"\",\n" +
                "        \"frequency\": \"\",\n" +
                "        \"content\": \"\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"executor\": \"\",\n" +
                "        \"planType\": \"\",\n" +
                "        \"frequency\": \"\",\n" +
                "        \"content\": \"\"\n" +
                "      }\n" +
                "    ]\n" +
                "  }\n" +
                "}" +rawData;


        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", prompt);

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", new JSONObject[]{message});

        RequestBody body = RequestBody.create(
                requestBody.toJSONString(),
                MediaType.get("application/json")
        );

        Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + DEEPSEEK_API_KEY)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("AI analysis failed: " + response);
            }
            String responseBody = response.body().string();
            return extractContentFromFullResponse(responseBody);
        }
    }

    /**
     * 使用远程 Python 服务计算语义相似度，选择最匹配的 FAQ（相似度 > 0.8 才有效）
     */
    private Faq findBestMatchWithRemoteModel(String userInput, List<Faq> candidates) {
        double maxSimilarity = -1.0;
        Faq bestMatch = null;

        for (Faq candidate : candidates) {
            try {
                double similarity = SimilarityClient.getSimilarity(userInput, candidate.getQuestion());
                if (similarity > maxSimilarity) {
                    maxSimilarity = similarity;
                    bestMatch = candidate;
                }
            } catch (IOException e) {
                log.error("计算语义相似度失败", e);
            }
        }

        // 只有当相似度大于 0.8 时才认为匹配有效
        return maxSimilarity > 0.8 ? bestMatch : null;
    }
}